import {ComponentOptions, PropType} from "vue/types/options";
import {Message} from "element-ui";
import {ElUpload} from "element-ui/types/upload";
import typeOfUtils from "../utils/type-of-utils";

/**
 el-upload的ref使用这个
 ref="uploadRef"
 */
const ElUploadMixin: ComponentOptions<any> = {
  props: {
    disabled: Boolean as PropType<boolean>,
    value: {
      type: Array as PropType<Array<any>>,
      default: () => []
    }
  },
  data() {
    return {
      getFileListFunRun: true,
      fieldAction: 'uploaderUrl',
      syncValue: [],
      headers: {
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Allow-Headers': 'origin,x-requested-with,content-type',
        'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
        'Access-Control-Allow-Origin': '*',
        Authorization: "Bearer "
      },
      fileList: [],
    }
  },
  computed: {
    uploadRef(): ElUpload {
      return this.$refs.uploadRef as ElUpload
    }
  },
  model: {
    prop: 'value',
    event: 'update:value'
  },
  watch: {
    value: {
      handler(val) {
        this.syncValue = val || []
        this.getFileList()
      },
      deep: true
    },
    syncValue: {
      handler(val) {
        this.$emit('update:value', val)
      },
      deep: true
    }
  },
  methods: {
    getFileList() {
      if (!this.getFileListFunRun) {
        this.getFileListFunRun = true
        return
      }
      this.fileList = []
      this.value.forEach(val => {
        val.downLoadName = val.downLoadName || val.fileName || val.name
        this.fileList.push({
          ...val,
          name: val.originalName || val.fileOriginalName,
          filePath: val.filePath || val.path,
          response: {
            data: {
              fileName: val.url
            }
          }
        })
      })
    },
    // 删除上传文件后
    handleRemove(file, fileList) {
      this.fileListToValue(fileList)
    },
    fileListToValue(fileList = []) {
      this.fileList = fileList
      this.syncValue = []
      this.getFileListFunRun = false
      fileList.forEach(val => {
        this.syncValue.push({
          ...val,
          name: val.name,
          downLoadName: val.downLoadName || val.response?.data.fileName,
          url: val.response?.data.fileName || val.url,
          fileId: val.response?.data.fileId || val.fileId,
          filePath: val.response?.data.path || val.filePath,
          originalName: val.response?.data.fileOriginalName || val.originalName
        })
      })
    },
    handleUploadError() {
      Message.error('上传失败')
    },
    handleAvatarSuccess(response, file, fileList = []) {
      if (response.code === 200) {
        this.fileListToValue(fileList)
      } else {
        fileList.splice(fileList.findIndex(i => i === file), 1)
        Message.error(response.msg)
      }
    },
    beforeAvatarUpload(file) {
      return true
    },
    handleExceed(files, fileList) {
      if (typeOfUtils.isNotEmpty(this.uploadRef.limit)) {
        Message.error(`文件最大上传${this.uploadRef.limit}个`)
      }
    },
    handleChange(file, fileList) {
      this.notAutoUploadToFileList(file, fileList)
    },
    notAutoUploadToFileList(file, fileList) {
      if (this.uploadRef.autoUpload !== true) {
        this.handleAvatarSuccess({
          code: 200
        }, file, fileList)
      }
    },
    __fileToFile(file) {
      return this.syncValue.find(i => i.fileId === file.fileId || i.fileId === file.response?.data?.fileId) || {}
    },
    /**
     * 点击附件名称下载附件
     * @param file 附件
     * @param fileList 附件列表
     */
    handlePreview(file, fileList) {
      file = this.__fileToFile(file)
      // 下载文件
      // downloadFile(file.path||file.filePath, file.downLoadName, file.originalName || file.fileOriginalName)
    },
    beforeRemove(file, fileList) { // 移除文件
      file = this.__fileToFile(file)
      if (file.fileId) {
        // return new Promise((resolve, reject) => {
        //   deleteFile([file.fileId]).then(res => {
        //     this.msgSuccess('删除完成')
        //     resolve()
        //   }).catch(err => {
        //     reject()
        //   })
        // })
        return true
      } else {
        return true
      }
    },
    onExceed() {
      Message.error('文件上传超出限制')
    },
    clear() {
      this.uploadRef.clearFiles()
    }
  }
}

export default ElUploadMixin

/**

 <template>
 <div>
 <el-upload
 ref="uploadRef"
 :action="fieldAction"
 drag
 :on-success="handleAvatarSuccess"
 :before-upload="beforeAvatarUpload"
 :on-error="handleUploadError"
 :on-remove="handleRemove"
 :on-change="handleChange"
 :on-exceed="handleExceed"
 :disabled="disabled"
 :auto-upload="true"
 :show-file-list="true"
 :file-list="fileList"
 :headers="headers"
 :accept="accept"
 >
 </el-upload>
 </div>
 </template>

 <script>
 import commonMixin from './mixins/commonMixin'

 export default {
  name: 'UploadImg',
  mixins:[commonMixin],
  data() {
    return {
      fileType:fileType.img
    }
  },
  computed:{
    accept(){
      return this.fileType.type.join(',')
    }
  },
  methods:{
    beforeAvatarUpload(file) {
      const isImage = this.fileType.type.includes(file.type)
      if (!isImage) {
        Message.error('上传的附件只能是 ' + this.fileType.name + ' 格式!')
      }
      return isImage
    }
  }
}
 </script>
 */


/**
 * 自定义实现 httpRequest 可以看一下这个

 const { uid } = rawFile;
 const options = {
        headers: this.headers,
        withCredentials: this.withCredentials,
        file: rawFile,
        data: this.data,
        filename: this.name,
        action: this.action,
        onProgress: e => {
          this.onProgress(e, rawFile);
        },
        onSuccess: res => {
          this.onSuccess(res, rawFile);
          delete this.reqs[uid];
        },
        onError: err => {
          this.onError(err, rawFile);
          delete this.reqs[uid];
        }
      };
 const req = this.httpRequest(options);
 this.reqs[uid] = req;
 if (req && req.then) {
        req.then(options.onSuccess, options.onError);
      }


 <el-upload action=""
 :before-upload="beforeAvatarUpload"
 :http-request="httpRequest"
 :on-success="onSuccess"
 >
 <el-button>导入数据</el-button>
 </el-upload>

 httpRequest({file}) {
      const formData = new FormData()
      formData.append('file',file)
      return submitSubjectUpload(this.detailId,formData)
    },
 onSuccess(response, file, fileList) {
      console.log(response);
    }

 *
 */
